package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService paramService;
    @Override
    public List<SpecGroupDTO> queryGroupsByCategory(Long cid) {

        return SpecGroupDTO.convertEntityList(query().eq("category_id",cid).list());
    }

    @Override
    public void addSpecGroup(SpecGroupDTO specGroupDTO) {
        save(specGroupDTO.toEntity(SpecGroup.class));
    }

    @Override
    public void updateSpeGroup(SpecGroupDTO specGroupDTO) {
        updateById(specGroupDTO.toEntity(SpecGroup.class));
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long cid) {
        List<SpecGroupDTO> specGroupDTOS = queryGroupsByCategory(cid);

        List<SpecParamDTO> specParamDTOS = SpecParamDTO
                .convertEntityList(
                        this.paramService
                                .query()
                                .eq("category_id", cid)
                                .list());

        //对specParamDTO的集合进行分组，按照groupId处理，map的key就是groupId，value此id对应的规格参数集合
        Map<Long, List<SpecParamDTO>> paramMap = specParamDTOS
                .stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        //循环给每个group赋值对应的param信息
        specGroupDTOS.forEach(specGroupDTO -> specGroupDTO.setParams(paramMap.get(specGroupDTO.getId())));


        return specGroupDTOS;
    }
    

}